package fitnesshub.service.impl;

import fitnesshub.exception.AccountNotFoundException;
import fitnesshub.exception.PasswordErrorException;
import fitnesshub.mapper.AdminMapper;
import fitnesshub.pojo.dto.AdminLoginDTO;
import fitnesshub.pojo.entity.Admin;
import fitnesshub.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;

@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;

    /**
     * 管理员登录
     * @param adminLoginDTO
     * @return
     */
    @Override
    public Admin login(AdminLoginDTO adminLoginDTO) {
        String username = adminLoginDTO.getUsername();
        String password = adminLoginDTO.getPassword();

        //根据用户名查询数据库中的数据
        Admin admin = adminMapper.getByUsername(username);

        //处理各种异常情况（用户名不存在、密码不对）
        if (admin == null) {
            //账号不存在
            throw new AccountNotFoundException("账号不存在");
        }

        //密码比对
        //已经进行md5加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(admin.getPassword())) {
            //密码错误
            throw new PasswordErrorException("密码错误");
        }

        //返回实体对象
        return admin;
    }

    public List<Admin> getAdminInfo()
    {
        List<Admin> adminList = adminMapper.getAdminInfo();
        for (Admin admin : adminList) {
            // 将密码属性设置为掩码形式（这里假设Admin类中有个名为password的属性用于存储密码）
            admin.setPassword("***");
        }
        return adminList;
    }

}
